package com.hq.common.initializer;

import com.hq.common.utils.ApplicationContextUtils;
import com.hq.common.utils.OrderableComparator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.web.context.WebApplicationContext;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @since 2015-02-05 10:32
 */
public class SystemInitializer implements ApplicationListener<ContextRefreshedEvent> {
    private final Logger logger = LoggerFactory.getLogger(SystemInitializer.class);

    /**
     * 在web 项目中（spring mvc），系统会存在两个容器，
     * 一个是root application context ,另一个就是mvc projectName-servlet  context（作为root application context的子容器）。
     * 这种情况下，会造成onApplicationEvent方法被执行两次，需要进行判断。
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext().getParent();
        if (applicationContext instanceof WebApplicationContext) {//root application context 没有parent.
            //需要执行的逻辑代码，当spring容器初始化完成后就会执行该方法
            logger.info("系统初始化！");
            ApplicationContextUtils.setApplicationContext(applicationContext);
            Collection<Initializer> initializers = ApplicationContextUtils.getBeanListOfType(Initializer.class);
            if (initializers != null && initializers.size() > 0) {
                List<Initializer> list = new ArrayList<Initializer>();
                list.addAll(initializers);
                OrderableComparator.sort(list);      //对系统中的初始化器进行排序

                for (Initializer initializer : list) {
                    initializer.initialize();     //执行初始化操作
                }
            }
            logger.info("===================================系统初始化完成！===========================================");
        }
    }

}
